package org.whereiswally.net.picturerepository.imp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.whereiswally.net.picturerepository.PictureRepository;

public class PicasaPictureRepository extends PictureRepository implements
	Serializable {

    private static Logger logger = Logger
	    .getLogger(PicasaPictureRepository.class);

    private static final String KEY = "\"media\":{\"content\":[{\"url\":\"";

    /**
     * @param uri
     */
    public PicasaPictureRepository(URI uri) {
	super(uri);
	// TODO Auto-generated constructor stub
    }

    public List<URI> getPicturesOfAlbum(URI albumURL) {
	List<URI> pictures = new ArrayList<URI>();
	try {
	    BufferedReader br = new BufferedReader(new InputStreamReader(
		    albumURL.toURL().openStream()));
	    String thisLine;
	    while ((thisLine = br.readLine()) != null) {
		if (thisLine.indexOf(KEY) != -1) {
		    String line = thisLine;
		    while (line.indexOf(KEY) != -1) {
			int ini = line.indexOf(KEY) + KEY.length();
			int fin = ini + line.substring(ini).indexOf("\"");
			pictures.add(new URI(line.substring(ini, fin)));
			line = line.substring(fin);
		    }
		}

	    }

	} catch (Exception e) {
	    e.printStackTrace();
	}

	return pictures;

    }

    public List<URL> getAlbumsOfRepository(URL albumURL) {
	throw new RuntimeException("Metodo no implementado!");
	// return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @seeorg.whereiswally.net.picturerepository.PictureRepositoryManager#
     * getAllPicturesOfRepository()
     */
    @Override
    public List<URI> getAllPicturesOfRepository() {
	return getPicturesOfAlbum(getUri());
    }

}
